<template>
  <div>
    <h1>Vue Watcher Sample</h1>
    <div><input type="text" v-model="num"></div>
    <div>Result is {{ result }}</div>
  </div>
</template>
<script>
export default {
  name: "WatcherSample",
  data() {
    return {
      num: 0,
      result: "",
      timer: null
    }
  },
  watch: {
    num: {
      handler(newValue) {
        this.result = "正在输入，请稍后";
        if (this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          this.result = Math.sqrt(newValue);
        }, 1000)
      },
      immediate: true,
    }
  },
  beforeDestroy() {
    if (this.timer) {
      clearTimeout(this.timer);
    }
  }
}
</script>

<style scoped>

</style>
